# encoding: utf-8
# !/usr/local/bin/python3

"""
@author: Gao Shuo
@contact: dorothy400@163.com
@software: PyCharm
@file: roof_concat.py
@time: 2020/4/24 17:01

input: 切分后的图片位置，整除像素切分
output: 合并后的存放地址
"""

import os.path
import sys

from PIL import Image

if __name__ == "__main__":
    ext = ".png"
    clip_width = 256
    clip_height = 256
    path_ori = sys.argv[1]
    dest = sys.argv[2]
    all_names = os.listdir(path_ori)
    img_names = [x.split('_')[0] for x in all_names]
    img_names = list(set(img_names)) # unique
    for img_name in img_names:
        print "Now processing " +img_name
        all_clipped = [x for x in all_names if x.split('_')[0] == img_name]
        all_i = [int(x.split('_')[1]) for x in all_clipped]
        all_i = list(set(all_i)) # unique
        all_i.sort()
        all_j = [int(x.split('_')[2].split('.')[0]) for x in all_clipped]
        all_j = list(set(all_j)) # unique
        all_j.sort()
        width = clip_width*len(all_i)
        height = clip_height*len(all_j)
        target = Image.new('RGB', (width, height))
        for i in all_i:
            for j in all_j:
                file_name = path_ori +'/'+ img_name +'_'+str(i) +'_'+str(j) +ext
                image = Image.open(file_name)
                xy = (clip_width*i, clip_height*j, clip_width*(i+1), clip_height*(j+1))
                target.paste(image, xy)
        target.save(dest+'/'+img_name+ext, quality = 100)



